package Team.Model.Login;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import Exception.SocketConnectionFailureException;
import Team.Controller.*;
import Team.Model.*;


import java.io.*;

public class Initialize
{
    public Initialize(TeamModel model)
    {
    	this.model = model;
    }
    
    public void initializeSeverIp()
	{
		try
		{
			BufferedReader in = new BufferedReader(new FileReader(this.ConfigureFilePath));
			serverIp = in.readLine();
			port = new Integer(in.readLine());
		}
		catch(FileNotFoundException exception)
		{
			System.out.println("FileNotFound : " + this.ConfigureFilePath);
			exception.printStackTrace();
		}
		catch(IOException exception)
		{
			System.out.println("IOException when read file : " + this.ConfigureFilePath);	
			exception.printStackTrace();
		}
		catch(Exception exception)
		{
			System.out.println("Exception happened when initializeServerIp");
			exception.printStackTrace();
		}
	}
    
    public boolean initializeSocket() throws SocketConnectionFailureException
	{
		try
		{
			this.model.socket = new Socket(serverIp, port);
			
			System.out.println("team socket has been created!");
		}
		catch(IOException exception)
		{
			exception.printStackTrace();
			throw new SocketConnectionFailureException("Cann't connect to server, Please contact the staff!");
		}
		return true;
	}
    
    public void initializeObjectInputStream()
    {
        try
        {
        	 this.model.setObjectInputStream(new ObjectInputStream(
             		new DataInputStream(this.model.socket.getInputStream())));
        }
        catch(IOException exception)
        {
        	exception.printStackTrace();
        }
    }
    
    public void initializeObjectOutputStream()
    {
    	try
    	{
    		this.model.setObjectOutputStream(new ObjectOutputStream(
             		new DataOutputStream(this.model.socket.getOutputStream())));
    	}
    	catch(IOException exception)
    	{
    		exception.printStackTrace();
    	}
    }
    
    private TeamModel model;
    
    private String serverIp;
	private int port;
	private String ConfigureFilePath = new String("c:\\server_process_address.txt"); 
}
